package com.lyw.springCloud.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.lyw.springCloud.dao.OrderDao;
import com.lyw.springCloud.domain.Order;
import com.lyw.springCloud.service.AccountService;
import com.lyw.springCloud.service.OrderService;
import com.lyw.springCloud.service.StorageService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Auther liyawei
 * @Date 2022/5/19 20:25
 */

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderDao orderDao;

    @Resource
    private StorageService storageService;

    @Resource
    private AccountService accountService;

    @Override
    @GlobalTransactional(name = "at-customer-order", rollbackFor = Exception.class)
    public void create(Order order) {

        log.info("-----------> 新建订单： {}", order);
        orderDao.insert(order);

        // 根据商品 id 做扣减
        log.info("-----------> 订单服务调用库存服务做扣减");
        storageService.decrease(order);
        log.info("-----------> 订单服务调用库存服务做扣减end");

        // 根据用户 id 做扣减
        log.info("-----------> 订单服务调用账户服务扣钱");
        accountService.decrease(order);

        LambdaUpdateWrapper<Order> wrapper = new UpdateWrapper<Order>().lambda();
        wrapper.set(Order::getStatus , 1).ge(Order::getUserId, order.getUserId());
        // 修改订单状态， 从0 到1  1代表已完成
        orderDao.update(order, wrapper);

        log.info("-----------> 新建订单结束");
    }
}
